<template>
	<my-bottom-popup :round="0">
		<view class="comfirm-order">
			<!-- 导航栏 -->
			<view class="navbar">
				<image class="back" src="/static/images/common/arrow-left.png" @click="onClose"></image>
				<view class="title">确认订单</view>
			</view>
			
			<scroll-view class="scroll-view" scroll-y>
				<!-- 选择服务地址 -->
				<view class="choose-address">
					<view v-if="!selectedAddress" class="placeholder">{{ addressList.length ? '请选择服务地址' : '请添加服务地址' }}</view>
					<view v-else>
						<view class="address">{{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.area }}{{ selectedAddress.street }}{{ selectedAddress.address }}</view>
						<view class="name">{{ selectedAddress.name }} {{ selectedAddress.mobile }}</view>
					</view>
					<u-icon name="arrow-right" color="#242424" size="24rpx" bold></u-icon>
				</view>
				
				<!-- 选择套餐 -->
				<view v-for="(sku, key) in skuData">
					<view class="choose-package">
						<view class="title">{{ key }}</view>
						<view class="package-list">
							<view
								v-for="(option) in sku.options"
								:class="['package', {'active': option === sku.value }]"
								:key="option"
								@click="changeSku(key, option)"
							>
								<view class="value">{{ option }}</view>
								<image v-if="option === sku.value" class="checked" src="/static/images/common/checked.png"></image>
							</view>
						</view>
					</view>
				</view>
				<!-- 增值服务 -->
				<view v-if="productDetail.productAddServicesList.length" class="form-item form-item-border-bottom value-added-services">
					<view class="title">增值服务</view>
					<view class="options">
						<view :class="['option', { active: orderForm.addServices.find(e => e.id === option.id) }]" v-for="option in productDetail.productAddServicesList" :key="option.id" @click="selectAddService(option)">
							<view class="name">{{ option.name }}</view>
							<view class="price">￥{{ toFixed(option.price) }}</view>
						</view>
					</view>
				</view>
				
				<!-- 选择上门时间 -->
				<view class="choose-time" @click="chooseServiceTime">
					<view class="title">上门时间</view>
					<view :class="['value', { placeholder: !orderForm.serviceStartTime }]">{{ formatServiceTime }}</view>
					<u-icon class="arrow-right-icon" name="arrow-right" color="#242424" size="24rpx" bold></u-icon>
				</view>
				
				<!-- 订单备注 -->
				<view class="form-item order-note">
					<view class="title">订单备注</view>
					<u--textarea
						v-model="orderForm.note"
						placeholder="请输入订单备注，100字以内"
						height="80rpx"
						border="none"
						fontSize="28rpx"
						:maxlength="100"
					/>
				</view>
			</scroll-view>
			
			<!-- 底部确认栏 -->
			<view class="bottom-confirm">
				<!-- 服务协议 -->
				<view class="service-agreement">
					<image class="check-icon" :src="`/static/images/master/order/${isCheckedAgreement ? 'checked' : 'uncheck'}.png`" @click="checkAgreement"></image>
					<view class="link" @click="openAgreement">《广州市家庭服务综合平台》服务协议</view>
				</view>
				<!-- 价格及下单按钮 -->
				<view class="place-order">
					<view class="paid">
						<view class="price">
							<text class="sybmol">￥</text>
							<text class="int">{{ cutDecimal(orderForm.totalAmount)[0] }}</text>
							<text class="decimal">{{ cutDecimal(orderForm.totalAmount)[1] }}</text>
						</view>
						<view class="tips">应付金额</view>
					</view>
					<button class="submit">立即下单</button>
				</view>
			</view>
		</view>
		<my-page-loading></my-page-loading>
	</my-bottom-popup>
</template>

<script lang="ts" setup>
	import { reactive, watch, watchEffect } from 'vue';
	import { toFixed, cutDecimal, redirectPage } from '@/utils';
	import useAddress from './useAddress';
	import useTime from './useTime';
	import useAgree from './useAgree'
	import MyPageLoading from '@/components/my-page-loading/my-page-loading.vue';
	import MyBottomPopup from '@/components/my-bottom-popup/my-bottom-popup.vue';
	
	const emits = defineEmits(['openAddress', 'openTime', 'openAgreement', 'update:show']);
	const props = defineProps({
		productDetail: {
			type: Object,
			default: () => ({}),
		},
	});
	
	// 下单表单
	const orderForm = reactive({
		// 产品ID
		productId: 0,
		// 产品数量
		productQuantity: 1,
		// 服务地址ID
		memberAddressId: 0,
		// 服务上门时间
		serviceStartTime: '',
		// 套餐编码
		skuCode: '',
		// 套餐ID
		skuId: '',
		// 增值服务
		addServices: [],
		// 订单备注
		note: '',
		
		// 下单来源 未知->1
		sourceType: 1,
		
		// 套餐价格
		promotionPrice: '',
		// 实际支付价格
		payAmount: 0,
		// 总价
		totalAmount: 0,
	});
	
	// 下单
	const createOrderNew = () => {
		if (!orderForm.memberAddressId) {
			uni.showToast({ title: '请选择服务地址', icon: 'none' });
			return;
		}
		if (!orderForm.serviceStartTime) {
			uni.showToast({ title: '请选择上门时间', icon: 'none' });
			return;
		}
		if (!isCheckedAgreement.value) {
			uni.showToast({ title: '请先勾选服务协议', icon: 'none' });
			return;
		}
	};
	
	const { addressList, chooseAddress, selectedAddress, setAddress } = useAddress(orderForm, emits);
	const { chooseServiceTime, setServiceTime, formatServiceTime } = useTime(orderForm, emits);
	const { isCheckedAgreement, openAgreement, checkAgreement } = useAgree(emits);
	
	// 关闭弹窗
	const onClose = (): void => {
		emits('update:show', false);
	};
	
	// 选择增值服务
	const selectAddService = (option: any) => {
		const index = orderForm.addServices.findIndex(item => item.id === option.id);
		if (index === -1) {
			orderForm.addServices.push({
				id: option.id,
				price: option.price,
				quantity: 1,
				numFlag: option.numFlag,
			});
		} else {
			orderForm.addServices.splice(index, 1);
		}
	}
	
	// sku数据
	const skuData = reactive<any>({});
	// 切换sku
	const changeSku = (key: string | number, value: string) => {
		skuData[key].value = value;
		try {
			props.productDetail.skuStockList.forEach((item: any) => {
				const selectedData = Object.keys(skuData).map(key => ({ key, value: skuData[key].value }));
				if (item.spData === JSON.stringify(selectedData)) {
					orderForm.promotionPrice = item.promotionPrice;
					orderForm.skuCode = item.skuCode;
					orderForm.skuId = item.id;
					throw '匹配成功，终止循环';
				}
			});
		} catch {}
	};
	watch(
		() => props.productDetail.attrProduct,
		(newVal) => {
			if (newVal) {
				newVal.forEach((item: any) => {
					Object.keys(item).forEach(key => {
						skuData[key] = { value: '', options: [] };
						Object.keys(item[key]).forEach((k, i) => {
							if (i === 0) {
								skuData[key].value = k
								changeSku(key, k);
							};
							skuData[key].options.push(k);
						});
					});
				});
			}
		},
	);
	// 获取产品ID
	watch(
		() => props.productDetail.id,
		(newId) => {
			orderForm.productId = newId;
		},
		{
			immediate: true,
		}
	);
	// 计算总价
	watchEffect(() => {
		let totalAmount = 0;
		totalAmount = props.productDetail.promotionPrice;
		if (orderForm.promotionPrice) {
			totalAmount = +orderForm.promotionPrice;
		}
		totalAmount = orderForm.addServices.map(item => item.price).reduce((acc, current) => {
			return acc + current;
		}, totalAmount);
		orderForm.totalAmount = totalAmount;
		orderForm.payAmount = totalAmount;
	});
	
	defineExpose({
		setAddress,
		setServiceTime,
	});
</script>

<style lang="scss" scoped>
	::v-deep .popup-body {
		padding: 0 !important;
	}
	::v-deep .popup-content {
		padding: 0 !important;
	}
	.comfirm-order {
		height: 100vh;
		padding: 0 40rpx;
	}
	.form-item {
		padding: 36rpx 0;
	}
	.form-item-border-bottom {
		border-bottom: 1rpx solid #EEE;
	}
	
	.navbar {
		height: 90rpx;
		position: relative;
		padding-top: calc(var(--status-bar-height) * 1.1);
		.back {
			width: 35rpx;
			height: 34rpx;
			position: absolute;
			left: 0;
			bottom: 28rpx;
		}
		.title {
			line-height: 90rpx;
			font-size: 36rpx;
			font-weight: 500;
			color: #242424;
			text-align: center;
		}
	}
	
	.scroll-view {
		height: calc(100vh - 90rpx - 220rpx - var(--status-bar-height) * 1.1);
	}
	
	.choose-address {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		background: #F4F5F8;
		border-radius: 16rpx;
		padding: 32rpx 24rpx;
		box-sizing: border-box;
		.placeholder {
			line-height: 36rpx;
			font-size: 28rpx;
			font-weight: bold;
			color: #242424;
		}
		.address {
			width: 580rpx;
			line-height: 28rpx;
			font-size: 28rpx;
			font-weight: bold;
			color: #242424;
			margin-bottom: 14rpx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
		.name {
			line-height: 24rpx;
			font-size: 24rpx;
			font-weight: 400;
			color: #707070;
		}
	}
	
	.choose-time {
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-right: 24rpx;
		border-bottom: 1rpx solid #eee;
		.title,
		.value {
			line-height: 28rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #242424;
		}
		.value {
			flex: 1;
			padding-left: 100rpx;
		}
		.placeholder {
			color: #AAAAAA !important;
		}
	}
	
	.choose-package {
		padding: 37rpx 0;
		border-bottom: 1rpx solid #eee;
		.title {
			line-height: 28rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #242424;
			margin-bottom: 26rpx;
		}
		.package-list {
			.active {	
				background: #EBF5F8 !important;
				border: 2rpx solid #3E9DBB !important;
			}
			.package {
				width: 100%;
				height: 120rpx;
				padding: 0 30rpx 0 28rpx;
				margin-bottom: 20rpx;
				line-height: 120rpx;
				font-size: 28rpx;
				font-weight: bold;
				color: #242424;
				background: #F4F5F8;
				border-radius: 16rpx;
				border: 2rpx solid #F4F5F8 !important;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: space-between;
				&:nth-last-child(1) {
					margin-bottom: 0;
				}
				.checked {
					width: 36rpx;
					height: 36rpx;
				}
			}
		}
	}
	
	.value-added-services {
		padding: 37rpx 0 17rpx;
		.title {
			line-height: 28rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #242424;
			margin-bottom: 20rpx;
		}
		.options {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			.option {
				width: 326rpx;
				height: 100rpx;
				padding: 22rpx 27rpx 0;
				margin-bottom: 20rpx;
				background: #F4F5F8;
				border: 2rpx solid #F4F5F8;
				border-radius: 16rpx;
				box-sizing: border-box;
			}
			.active {
				background: #EBF5F8;
				border: 2rpx solid #3E9DBB;
			}
			.name {
				line-height: 24rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #242424;
				margin-bottom: 16rpx;
			}
			.price {
				line-height: 24rpx;
				font-size: 24rpx;
				font-weight: bold;
				color: #242424;
			}
		}
	}
	
	.order-note {
		display: flex;
		padding: 32rpx 0 !important;
		.title {
			width: 210rpx;
			line-height: 28rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #242424;
			margin-top: 5rpx;
		}
		.u-textarea {
			padding: 0;
		}
	}
	
	.bottom-confirm {
		position: relative;
		padding: 32rpx 40rpx 20rpx;
		left: -40rpx;
		width: 750rpx;
		height: 220rpx;
		background: #FFFFFF;
		border-top: 1rpx solid #E4E4E4;
		box-sizing: border-box;
	}
	
	.service-agreement {
		height: 36rpx;
		display: flex;
		align-items: center;
		margin-bottom: 44rpx;
		.check-icon {
			width: 38rpx;
			height: 38rpx;
			display: block;
		}
		.link {
			line-height: 36rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #3E9DBB;
			margin-left: 10rpx;
		}
	}
	
	.place-order {
		height: 88rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.paid {
			.price {
				display: flex;
				align-items: flex-end;
				font-weight: bold;
				color: #EB4836;
				margin-bottom: 12rpx;
				.sybmol {
					line-height: 24rpx;
					font-size: 24rpx;
				}
				.int {
					line-height: 44rpx;
					font-size: 44rpx;
				}
				.decimal {
					line-height: 36rpx;
					font-size: 36rpx;
				}
			}
			.tips {
				line-height: 24rpx;
				font-size: 24rpx;
				font-weight: 400;
				color: #242424;
			}
		}
		.submit {
			width: 432rpx;
			height: 88rpx;
			background: #3E9DBB;
			border-radius: 16rpx;
			margin: 0;
			line-height: 88rpx;
			font-size: 32rpx;
			font-weight: 500;
			color: #FFFFFF;
			&::after {
				border: 0;
			}
		}
	}
</style>